import RowModel from "../../cfw/mvc/RowModel";
import DataManager from "./DataManager";

export default class DataItemModel extends RowModel {
    protected fileName: string = ''
    // protected data: any[] = null;


    constructor(name: string) {
        super();
        this.setFileName(name)
    }

    reset(id: any, data?: any[], ...param: any) {
        this.setID(id)
        this._cfg = data;
    }

    //默认ID从1开始的那种才可以调用此函数。
    getIndex() {
        return this.ID - 1;
    }
    setFileName(name: string) {
        this.fileName = name;
    }

    getFileName() {
        return this.fileName;
    }

    setValue(index: number, value: any, isSave: boolean = true) {
        DataManager.instance().setValue(this.fileName, this.ID, index, value, isSave)
        this.emit(this.getEventKey(index), value)
    }

    getCfgValue(index: number) {
        return DataManager.instance().getCfgValue(this.fileName, this.ID, index)
    }

    getValue(index: number, initValue?: any) {
        return DataManager.instance().getValue(this.fileName, this.ID, index, initValue)
    }

    saveValue(index: number) {
        DataManager.instance().saveDBValue(this.fileName, this.ID, index)
    }

    getEventKey(index: number) {
        return this.fileName + this.ID + index
    }


    static getNewModel<T extends DataItemModel>(id: string, type: { new(): T; }) {
        let ins = new type();
        ins.reset(id)
        return ins;
    }

    static getNewModelByKey<T extends DataItemModel>(id: string, type: { new(): T; }) {
        let model = this.getNewModel(id, type)
        model.setKey(Date.now() + id)
        return model;
    }
}